import random
from langchain_core.tools import tool

@tool
def multiply(first_int: int, second_int: int) -> int:
    """将两个整数相乘。"""
    return first_int * second_int

@tool
def add(first_int: int, second_int: int) -> int:
    "将两个整数相加。"
    return first_int + second_int

@tool
def exponentiate(base: int, exponent: int) -> int:
    "对底数求指数幂。"
    return base**exponent

@tool
def say(word: str) -> str:
	"输出字符串"
	return f"say: {word}"

tools_calc = [multiply, add, exponentiate]
tools_say = [say]

import json
from langchain_core.messages import ( AIMessage, BaseMessage, )
def exec_call(message: BaseMessage) -> str:
    """Exec `function_call` from `AIMessage`."""
    if isinstance(message, AIMessage):
        kwargs = message.additional_kwargs
        tool_calls = message.tool_calls
        if len(tool_calls) > 0:
            tool_call = tool_calls[-1]
            tool_call_name = tool_call.get("name")
            tool_call_args = tool_call.get("args")

            print(tool_call_name, tool_call_args)
            func = globals().get(tool_call_name)
            if func is not None and callable(func):
                #ret = func(**tool_call_args)
                ret = func.invoke(tool_call_args)
                print(ret)
            else:
                print(f"Unknown function: {tool_call_name}")
        elif "function_call" in kwargs:
            if "arguments" in kwargs["function_call"]:
                return kwargs["function_call"]["arguments"]
            raise ValueError(
                f"`arguments` missing from `function_call` within AIMessage: {message}"
            )
        else:
            raise ValueError("`tool_calls` missing from AIMessage: {message}")
    else:
        raise ValueError(f"`message` is not an instance of `AIMessage`: {message}")
